<template>
    <div class="wrap">
        <head-title :title="headText" @callback="onClickLeft"></head-title>
        <div class="wrapbd trade_count">
            <div class="tittab"><span><router-link to="/lbuyin?id=0">构树链交易</router-link></span><span class="active"><router-link to="/mbuyin?id=0">构树苗交易</router-link></span></div>
            <ul class="tablist" id="istab"><li :class="{'active' : index == activeid}" v-for="(item,index) in tabsTit" :key="index" @click="requeInt(index)">{{item}}</li></ul>
            <div class="tables" v-show="activeid == 0">
                <div class="tit"><span>昵称</span><span>价格</span><span>数量</span><span>支付方式</span><span>操作</span></div>
                <ul>
                    <li v-for="(item,index) in tradeDataArr" :key="index"><span>{{item.nick_name}}</span><span>{{item.unit_price | nubFixed}}</span><span>{{item.num | nubFixed}}</span><span v-html="paytypeTrans(item.pay_type)"></span><span><input class="tabin" type="button" value="买入" @click="buyInOut(item.order_no,2)" v-show="item.handle == 1"><i v-show="item.handle == 0">--</i></span></li>
                    <p v-if="page != pageNum && tradeDataArr.length != 0" @click="onLoad(1)">加载更多</p>
                    <p v-if="page == pageNum || tradeDataArr.length == 0">没有更多数据</p>
                </ul>
            </div>
            <div class="tables" v-show="activeid == 1">
                <div class="tit"><span>昵称</span><span>价格</span><span>数量</span><span>支付方式</span><span>操作</span></div>
                <ul>
                    <li v-for="(item,index) in tradeDataArr" :key="index"><span>{{item.nick_name}}</span><span>{{item.unit_price | nubFixed}}</span><span>{{item.num | nubFixed}}</span><span v-html="paytypeTrans(item.pay_type)"></span><span><input class="tabout" type="button" value="卖出" @click="buyInOut(item.order_no,3)" v-show="item.handle == 1"><i v-show="item.handle == 0">--</i></span></li>
                    <p v-if="page != pageNum && tradeDataArr.length != 0" @click="onLoad(2)">加载更多</p>
                    <p v-if="page == pageNum || tradeDataArr.length == 0">没有更多数据</p>
                </ul>
            </div>
            <div class="tables" v-show="activeid == 2">
                <div class="putOrder">
                    <div class="pt">
                        <span>挂单</span>
                        <radio-group v-model="radio" class="isradio">
                            <radio name="1" style="margin-right:.5rem;">买入</radio>
                            <radio name="2">卖出</radio>
                        </radio-group>
                    </div>
                    <div class="pt"><span>数量</span><input type="tel" v-model.trim="num" placeholder="请输入数量"></div>
                    <div class="pt"><span>价格</span><input type="tel" v-model.trim="price" placeholder="请输入价格"></div>
                    <div class="pt">
                        <span>联系方式</span>
                        <checkbox-group v-model="isresult" class="isradio">
                            <checkbox v-for="(item, index) in contObj" :disabled="item == 0" :key="index" :name="index" class="margin_r">{{ index | contactType }}</checkbox>
                        </checkbox-group>
                    </div>
                    <div class="pt">
                        <span>支付方式</span>
                        <checkbox-group v-model="result" class="isradio">
                            <checkbox v-for="(item, index) in list" :disabled="item == 0" :key="index" :name="index" class="margin_r" v-if="(index == 1 || index == 2) || radio == 2">{{ index | payType }}</checkbox>
                        </checkbox-group>
                    </div>
                    <div class="pts">温馨提示：银行卡为默认银行卡</div>
                    <input class="l_button" type="button" value="发布" :disabled="disableBtn" @click="publish">
                </div>
            </div>
            <div class="tables tablessix" v-show="activeid == 3">
                <div class="tit"><span>时间</span><span>买/卖</span><span>价格</span><span>数量</span><span>支付方式</span><span>操作</span></div>
                <ul>
                    <li v-for="(item,index) in tradeDataArr" :key="index"><span>{{item.create_time | mdDate}}</span><span :class="{'red':item.show == '买','green':item.show == '卖'}">{{item.show}}</span><span>{{item.unit_price | nubFixed}}</span><span>{{item.num | nubFixed}}</span><span v-html="paytypeTrans(item.pay_type)"></span><span><input class="revoke" type="button" value="撤单" @click="cancelOrder(item.order_no)"></span></li>
                    <p v-if="page != pageNum && tradeDataArr.length != 0" @click="onLoad(3)">加载更多</p>
                    <p v-if="page == pageNum || tradeDataArr.length == 0">没有更多数据</p>
                </ul>
            </div>
            <div class="tables" v-show="activeid == 4">
                <div class="tit"><span>时间</span><span>买/卖</span><span>成交价</span><span>成交量</span><span>支付方式</span></div>
                <ul>
                    <li v-for="(item,index) in tradeDataArr" :key="index">
                        <span>{{item.create_time | mdDate}}</span><span :class="{'red':item.show == '买','green':item.show == '卖',}">{{item.show}}</span><span>{{item.unit_price | nubFixed}}</span>
                        <span>{{item.num | nubFixed}}</span><span v-html="paytypeTrans(item.pay_type)"></span></li>
                    <p v-if="page != pageNum && tradeDataArr.length != 0" @click="onLoad(5)">加载更多</p>
                    <p v-if="page == pageNum || tradeDataArr.length == 0">没有更多数据</p>
                </ul>
            </div>
        </div>
        <div class="passwodInt" v-show="psdType">
            <password-input :value="payPsd" info="密码为 6 位数字" @focus="showKeyboard = true" />
            <number-keyboard :show="showKeyboard" @input="onInput" @delete="onDelete" @blur="showKeyboard = true"/>
        </div>
        <div class="fade" v-show="psdType" @click="psdType = false"></div>
    </div>
</template>
<script>
    import HeadTitle from "./../../components/title.vue";   
    import { Tab, Tabs, Radio, RadioGroup, Checkbox, CheckboxGroup, PasswordInput, NumberKeyboard, Dialog } from 'vant';
    export default {
        data(){
            return {
                a:false,
                b:false,
                c:false,
                headText: '交易大厅',  //顶部标题
                tabsTit:['买入','卖出','挂单','撤单','成交'],
                activeid: this.$route.query.id,
                radio: '1',
                contObj:{1:1,2:1,3:1},
                list: [],  //支付类型
                result: [], //选中的支付类型
                resultArr:[],  //传递给后台的 (被选中的支付类型)
                isresult:[],  //选中的联系方式
                isresultArr:[], //传递给后台的 (被选中的联系方式)
                tradeDataArr:[],   //列表数据
                num:'',  //数量
                price:'',  //价格
                payPsd:'',   //支付密码
                disableBtn:false,  //防止重复提交
                psdType:false,
                showKeyboard:true,
                pageNum:'',  //总页数
                page:1,  //页数
            }
        },
		mounted(){
            let t_nav = document.getElementById('istab');
            this.Tools.tabSwitch({li:t_nav.getElementsByTagName('li')});  //tab切换
            this.obtainPayType();   //默认获取支付类型
            this.orderPrice();
            this.$route.query.id == 0 ? this.tradeData({l_type: 1}) : this.$route.query.id == 1 ? this.tradeData({l_type: 2}) : this.tradeData({l_type: 3});
        },
        methods:{
            //返回
            onClickLeft () { this.$router.push('/mtrade');},
            //tab切换
            requeInt(id) {
                this.tradeDataArr = [];   //清空数据
                this.page = 1;  //切换时将页数设为1
                switch(id){
                    case 0:
                        this.activeid = 0;
                        this.tradeData({l_type: 1});   //买入
                    break;
                    case 1:
                        this.activeid = 1;
                        this.tradeData({l_type: 2});   //卖出
                    break;
                    case 2:
                        this.activeid = 2;   //挂单
                        this.orderPrice();  //获取价格
                    break;
                    case 3:
                        this.activeid = 3;
                        this.tradeData({l_type: 3});   //撤单
                    break;
                    case 4:
                        this.activeid = 4;
                        this.tradeData({l_type: 5});   //成交
                    break;
                }
            },
            //订单列表数据
            tradeData(json){
                let _this = this;
                this.Tools.AXIOS({
                    url: 'trade/list',
                    transformRequest:{
                        b_type: 2,
                        l_type: json.l_type,
                        page: this.page || 1,
                    },
                    success: function (res) {
                        _this.pageNum = res.data.data.pageNum;
                        _this.tradeDataArr.push(...res.data.data.list);
                    }
                })    
            },
            //买入,卖出操作
            buyInOut(orderId,typeId){
                let _this = this;
                this.Tools.AXIOS({
                    url: 'trade/operate',
                    transformRequest:{
                        order_no: orderId,
                        operate_type: typeId,
                    },
                    success: function (res) {
                        _this.$router.push({path:'myorderDetail',query: {ordid:orderId}});
                    },error(res){}
                })    
            },
            //挂单获取价格
            orderPrice(){
                let _this = this;
                this.Tools.AXIOS({
                    url: 'trade/coinprice',
                    transformRequest:{
                        b_type: 2,
                    },
                    success: function (res) {
                       _this.price = res.data.data;
                    },error(res){}
                })    
            },
            //撤单操作
            cancelOrder(id){
                let _this = this;
                Dialog.confirm({
                    title: '温馨提示',
                    message: '确定撤销订单？',
                }).then(() => {
                    this.Tools.AXIOS({
                        url: 'trade/operate',
                        transformRequest:{
                            order_no: id,
                            operate_type: 8,
                        },
                        success: function (res) {
                            _this.$toast.success('已撤销订单');
                            _this.tradeDataArr = [];   //清空数据
                            _this.tradeData({l_type: 3});   //撤单
                        },error(res){}
                    })    
                });           
            },
            //分页加载
            onLoad(id) {
                if(this.page < this.pageNum){
                    this.page++;
                    this.tradeData({l_type: id}); 
                }
            },
            //获取支付类型
            obtainPayType(){
                let _this = this;
                this.Tools.AXIOS({
                    url: 'trade/getpaytype',
                    success: function (res) {
                        _this.list = res.data.data;
                        Object.values(_this.list)[0] == 0 ?  _this.contObj[1] = 0 : '';
                        Object.values(_this.list)[1] == 0 ?  _this.contObj[2] = 0 : '';
                    }
                })
            },
            //挂单发布
            publish(){
                if(!this.Tools.regCombination.null.test(this.num)){
                    this.$toast({message: '请输入数量', position: 'bottom',duration: 1500})
                }else if(!this.Tools.regCombination.null.test(this.price)){
                    this.$toast({message: '请输入价格', position: 'bottom',duration: 1500})
                }else if(Object.values(this.list)[0] + Object.values(this.list)[1] + Object.values(this.list)[2] == 0){
                    this.$toast({message: '请先开通支付方式', position: 'bottom',duration: 1500})
                }else if(this.result.length == 0){
                    this.$toast({message: '请选择支付方式', position: 'bottom',duration: 1500})
                }else{
                    this.psdType = true;  //调起 支付密码 页面
                }
            },
            //支付方式转换为图标
            paytypeTrans(pay_type){
                let arr = pay_type.split(',')
                let map = new Map([
                    ['1','<span class="w"></span>'],
                    ['2','<span class="z"></span>'],
                    ['3','<span class="y"></span>'],
                ]);
                return Array.join(arr.map((key,val)=>{
                    return map.get(key);
                })).replace(new RegExp(/(,)/g),' ')
            },
            //输入支付密码
            onInput(key) {
                var _this = this;
                this.payPsd = (this.payPsd + key).slice(0, 6);
                if(this.payPsd.length == 6){
                    this.psdType = false;
                    this.publishPutup({
                        tips: 1,
                        callBack: function(res){
                            let result = res.data.data;
                            Dialog.confirm({
                                title: '温馨提示',
                                message: _this.radio == 1 ? ('该笔订单交易总额：'+ result.total_price + 
                                '元'):('该笔订单交易总额：'+ result.total_price + 
                                '元,  手续费收取：' + result.commission_num + 
                                '个构树链'),
                            }).then(() => {
                                _this.publishPutup({
                                    callBack: function(res){
                                        _this.$toast.success('发布成功');
                                        _this.result = [],_this.isresult = [], _this.num = '',_this.payPsd= '',   //清空
                                        _this.disableBtn = false;
                                    }
                                })
                            }).catch(() => {
                                _this.result = [],_this.isresult = [], _this.num = '',_this.payPsd= '';   //清空
                                _this.disableBtn = false;
                            });
                        }
                    })
                }
            },
            //发布挂单接口
            publishPutup(json){
                var _this = this;
                this.resultArr = [];   //清空数据
                this.isresultArr = [];   //清空数据
                this.isresult.forEach((item) => {this.isresultArr.push(item)});   //将支付类型转换成json格式
                this.result.forEach((item) => {this.resultArr.push(item)});   //将支付类型转换成json格式
                this.disableBtn = true;  //禁用按钮，防止重复提交
                this.Tools.AXIOS({    //发布挂单
                    url: 'trade/add',
                    transformRequest:{
                        b_type: 2,
                        trade_type: this.radio,
                        num: this.num,
                        unit_price: this.price,
                        contact: this.isresultArr.join(','),  //联系方式
                        pay_type: this.resultArr.join(','),  //支付方式
                        pay_pwd: this.payPsd,
                        tips:json.tips,
                    },
                    success: function (res) {
                        json.callBack(res);
                    },error(res){
                        _this.payPsd= '',   //清空
                        _this.disableBtn = false;
                    }
                })
            },
            //删除支付密码
            onDelete() {
                this.payPsd = this.payPsd.slice(0, this.payPsd.length - 1);
            },
        },
        components:{
            HeadTitle,
            Tab,Tabs,
            Radio,RadioGroup,
            Checkbox, CheckboxGroup,
            PasswordInput, NumberKeyboard,Dialog
        }
    }
</script>
<style scoped>
.tittab{ width: 100%; display: flex; justify-content: space-around; text-align: center; background: #fff; border-bottom: 1px solid #F3F3F3;}
.tittab span{ width: 50%; padding: .3rem 0; font-size: .4rem;}.tittab span a{ color: #666;}
.tittab span.active{ color: red; border-bottom: 2px solid red;}.tittab span.active a{ color:red;}
.tablist{ width: 90%; border: 1px solid #337AB7; overflow: hidden; border-radius: 3px; text-align: center; background: #fff; margin: .5rem auto;}
.tablist li{ width: 20%; padding: .2rem 0; float: left; border-right: 1px solid #337AB7; box-sizing: border-box;}
.tablist li:nth-last-of-type(1){ border: 0;}
.tablist li.active{ background: #337AB7; color: #fff;}
.trade_count{ width: 100%; background: #fff;}
.trade_count .tables{ width: 100%; overflow: hidden;}
.trade_count .tables ul{ background: #fff;}
.trade_count .tables li span,.trade_count .tables div span{ position: relative; width: 20%; float: left; text-align: center; font-size: .35rem; color: #000;}
.trade_count .tablessix li span,.trade_count .tablessix div span{ width: 16.6666%;}
.trade_count .tables li{ padding: .3rem 0; overflow: hidden; border-bottom: 1px solid #F6F6F6;}
.trade_count .tables .tit{ overflow: hidden; background: #fff; padding: .3rem 0; border-bottom: 1px solid #F6F6F6; border-top: 1px solid #F6F6F6}
.trade_count .tables p{ color: #ccc; padding: .3rem 0; text-align: center;}
.trade_count .tables li input{ color: #fff; border-radius: 3px; padding: .1rem .3rem; position: absolute; left: .3rem; top:-.1rem;}
.tabin{ background: #C93E0A;}.tabout{ background: green;}.revoke{ background: #337AB7;}
.trade_count .putOrder{ width: 95%; margin: 0 auto; padding: 0 0 .8rem;}
.trade_count .putOrder .pt{ width: 100%; display: flex; margin: .6rem 0;}
.trade_count .putOrder .pt span{ width: 18%; font-size: .32rem; line-height: .75rem;}
.trade_count .putOrder .pt input{ border: 1px solid #ccc; text-align:left; background: #fff; height: .75rem; width: 71%; font-size: .3rem; text-indent: .2rem; border-radius: 3px;}
.trade_count .putOrder .l_button{ padding: .2rem 0; border-radius: 3px; margin: 7% auto 0;}
.isradio{ width:75%; display: flex; margin-top: .1rem;}.ptcheck{ margin-left: 6%;}.margin_r{margin-right: 6%;}
.pts{ width: 100%; font-size: .30rem; margin: .5rem 0; text-indent: .5rem; color: red;}
</style>